package chat

import (
	"encoding/json"
	"fmt"
	"im/model/request"
	"time"

	"github.com/gorilla/websocket"
)

// 客户端信息
type Client struct {
	Hub  *Hub
	Conn *websocket.Conn
	// Buffered channel of outbound messages.
	Send   chan []byte
	UserId uint
}

// 发送消息
func (c *Client) WriteDump() {
	fmt.Println("-------- WriteDump")
	defer func() {
		c.Hub.Unregister <- c
		c.Conn.Close()
	}()

	for {
		// 写入消息
		msgReq := <-c.Send
		fmt.Println("data: ", string(msgReq))
		format := time.Now().Format("2006-01-02 15:04:05")
		message := fmt.Sprintf("[ws][%s]:%s", format, string(msgReq))
		if err := c.Conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
			errInfo := fmt.Sprintf("写入消息失败: %v\n", err.Error())
			fmt.Println(errInfo)
		}
	}
}

// 接收消息消息
func (c *Client) ReadDump() {
	fmt.Println("-------- ReadDump")
	defer func() {
		c.Hub.Unregister <- c
		c.Conn.Close()
	}()
	for {
		// 获取消息
		messageType, msg, err := c.Conn.ReadMessage()
		fmt.Println("message type: ", messageType)
		if err != nil {
			fmt.Println("接收消息失败...")
			// 当客户端关闭连接时，获取该连接消息通道关闭
			break
		}
		var messageReq request.MessageReq
		handlerMessage(msg, &messageReq)

		fmt.Println("接收的消息内容: ", messageReq)
		if err == nil {
			// 解析消息体
			b, _ := json.Marshal(messageReq)

			chatType := messageReq.Type
			switch chatType {
			case 1:
				// 私聊
				fmt.Println("-----私聊")
				c.Hub.PrivateChat <- &messageReq
			case 2:
				// 群聊
				fmt.Println("-----群聊")
				c.Hub.GroupChat <- &messageReq
			case 3:
				// 广播
				fmt.Println("-----广播")
				c.Hub.Boardcast <- b
			}

			fmt.Println("接收的消息内容: ", string(b))
		}
	}
}

/**
{
    "fromUserId":3,
    "targetUserId":5,
    "content":"测试",
    "type":"1",
    "media":"1"
}
*/
// 解析消息的请求参数
func handlerMessage(data []byte, messageReq *request.MessageReq) {
	// 从 conn 中获取userId、targeId、Message
	json.Unmarshal(data, &messageReq)
}
